#include "Sem.hpp"
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <random>
#include <ctime>
using namespace std;

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());

    // 创建建造者
    std::shared_ptr<SemaphoreBuilder> builder = std::make_shared<ConcreateSemaphoreBuilder>();
    auto director = std::make_shared<Director>();

    // 建造者指挥建造者进行建造
    director->Concreate(builder, BUILD_SEM, 0600, {1, 2, 3}, 3);

    auto fsem = builder->GetSemaPhore();

    int pid = fork();
    if (pid == 0)
    {
        auto csem = builder->GetSemaPhore();
        // 子进程
        int cnt = 10;
        while (cnt--)
        {
            csem->P(0);
            printf("C");
            usleep(rand() % 97532);
            fflush(stdout);
            printf("C");
            usleep(rand() % 43999);
            fflush(stdout);
            csem->V(0);
        }
        exit(0);
    }

    // 父进程
    int cnt = 20;
    while (cnt--)
    {
        fsem->P(0);
        printf("F");
        usleep(rand() % 97532);
        fflush(stdout);
        printf("F");
        usleep(rand() % 43999);
        fflush(stdout);
        fsem->V(0);
    }
    return 0;
}